import { Body, Injectable, Param } from '@nestjs/common';
import { IResponse } from 'src/interfaces/response.interface';
import { User } from 'src/schemas/user.schema';
import { UserService } from 'src/modules/user/user.service';
import { encrypt } from 'src/utils/encryption';
import { to } from 'src/utils/to';
import { JwtService } from '@nestjs/jwt';

@Injectable()
export class AuthService {
  private response: IResponse;
  constructor(
    private readonly userService: UserService,
    private readonly jwtService: JwtService,
  ) {}

  /**
   * @description 用户登陆验证
   * @date 2021-10-05
   * @param {User} user
   * @returns {*}
   */
  private async validateUser(user: User) {
    const phone = user.phone;
    const password = user.password;
    const [err, dbUser] = await to(this.userService.findOneByPhone(phone));
    try {
      if (err) throw Error(err);
      else if (!dbUser) {
        this.response = { code: 3, msg: '用户尚未注册' };
        throw this.response;
      } else {
        const pass = encrypt(password, dbUser.salt);
        if (pass === dbUser.password) {
          this.response = { code: 0, msg: '登陆成功' };
        } else {
          this.response = { code: 4, msg: '密码错误' };
          throw this.response;
        }
      }
    } catch (error) {
      return error;
    }
    return this.response;
  }

  /**
   * @description 用户登陆方法
   * @date 2021-10-05
   * @param user
   * @returns {*}
   */
  public async login(user: User) {
    return await this.validateUser(user).then(() => {
      return this.createToken(user);
    });
  }

  /**
   * @description 创建token
   * @date 2021-11-26
   * @param maya
   * @returns {*}
   */
  private async createToken(user: User) {
    return await this.jwtService.sign(user);
  }
}
